import logging
import env

env.loadEnv(globals(), ('REPYTHON_LOGGING', env.STRING, 'ERROR'), ('COLOR', env.UNSIGNED, 1))

class Formatter:
        def __init__(self):
                pass

        def format(self, data):
                #print data.__dict__
                #return ''.format(data)
                #return str(int(data.created)) + ';' + str(data.msecs)
                return '%0.3f | %s -> %s | %s | %s | %s' % (int(data.created) + data.msecs/1000, data.processName.ljust(12,' '), data.threadName.ljust(12,' '), str(data.module+'.'+data.funcName+'()').ljust(30, ' ')+str(': '+str(data.lineno)).rjust(6, ' '), data.levelname.center(9,' '), data.msg)
                pass

class ColorFormatter:
        def __init__(self):
                pass

        def format(self, data):
                #print data.__dict__
                #return ''.format(data)
                #return str(int(data.created)) + ';' + str(data.msecs)
                colors = {
                        'ERROR': RED,
                        'WARNING': YELLOW,
                        'EXCEPTION' : RED,
                        'DEBUG': CYAN,
                        'INFO': GREEN,
                        'CRITICAL': RED
                }
                return color(color=colors[data.levelname])+'%0.3f | %s -> %s | %s | %s | %s' % (int(data.created) + data.msecs/1000, data.processName.ljust(12,' '), data.threadName.ljust(12,' '), str(data.module+'.'+data.funcName+'()').ljust(30, ' ')+str(': '+str(data.lineno)).rjust(6, ' '), data.levelname.center(9,' '), data.msg)+color()
                pass

#logging.basicConfig(level=logging.DEBUG, format='%(created)d.%(msecs)03d | %(module)-15s : %(lineno)4d | %(levelname)-9s | %(message)s')
log = logging.getLogger('wython')
sh = logging.StreamHandler()
sh.setFormatter(ColorFormatter() if COLOR else Formatter())

log.addHandler(sh)

log.setLevel(REPYTHON_LOGGING.upper())

def logToFile(fname):
        fh = logging.FileHandler(fname)
        fh.setFormatter(Formatter())
        log.addHandler(fh)

BLACK=0
RED=1
GREEN=2
YELLOW=3
BLUE=4
PURPLE=5
CYAN=6
WHITE=7

NORMAL=0
BOLD=1
UNDERLINE=4

def color(color = None, style = NORMAL, background = None):
        if color is None and background is None:
                return chr(27)+'[0m'
        return (chr(27) + '[%dm'%background+40 if background is not None else '') + chr(27)+'[%d;%dm' % (style, color+30)

#log.setFormatter()

def quiet():
        log.setLevel(logging.ERROR)
